package kku.cs.fgl.actor;

import java.util.Vector;

import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;

import kku.cs.fgl.Actor;
import kku.cs.fgl.SpriteCell;
import kku.cs.fgl.SpriteSheet;

public class AnimateActor extends Actor {
    private int delay = 100;
	private Vector frames = new Vector();
	private SpriteCell frame=null;
	private int curFrame=0;
	private boolean active=true;
	
	public AnimateActor(int delay) {
       this.delay=delay;
	}

	public AnimateActor(float x, float y,int delay) {
  	   super(x, y);
       this.delay=delay;
	}

	public AnimateActor() {
		
	}

	public SpriteCell getFrame(int no){
		if(no<frames.size()){
			return (SpriteCell)frames.get(no);
		}
		return null;
	}
	public int add(SpriteSheet sheet,int cellNo){
		SpriteCell c=sheet.getCell(cellNo);
		frames.add(c);
		return frames.size();
	}
	public void add(SpriteSheet sheet,String cellList){
		String v[]=cellList.split(",");
		for(int i=0;i<v.length;i++){
		  if(v[i].length()==0) continue;
		  try{
		  int cellNo = Integer.parseInt(v[i]);		  
		  SpriteCell c=sheet.getCell(cellNo);
		  frames.add(c);
		  }catch(Exception e){}
		}		
	}
	public void add(SpriteCell[] cells){
		for(int i=0;i<cells.length;i++){
			frames.add(cells[i]);
		}
	}
	public void clear(){
		frames.clear();
	}
	public void next(){
		curFrame++;
		if(curFrame>=frames.size())curFrame=0;
		   frame = getFrame(curFrame);
		  if(frame!=null){
			setWidth(frame.getWidth());  
			setHeight(frame.getHeight());  
		  }
	}

	public void paint(Graphics g) {		
		if(frame!=null){
		   frame.paint(g,0,0,getFilter());
		}
	}

	private int ntime=0;
	public void update(int time) {
		super.update(time);
		if(active){
		  ntime+=time;
		  while(ntime>delay){
			  ntime-=delay;
			  next();
		  }
		}
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	public int getCurFrame() {
		return curFrame;
	}

	public void setCurFrame(int curFrame) {
		if(curFrame>=0 && curFrame<frames.size())
		this.curFrame = curFrame;
	}

	public int getDelay() {
		return delay;
	}

	public void setDelay(int speed) {
		if(speed>5)this.delay = speed;
	}

	public boolean contains(float x2, float y2) {
		boolean t=super.contains(x2, y2);		
		if(!t || frame==null)return t;
		
		int cx=(int)((x2-getX())/getScalex());
		int cy=(int)((y2-getY())/getScaley());
		Color c=frame.getPixel(cx,cy);
		return c.a>0f;
	}	
}


